package app.web.qk.service.impl;

import app.config.Config;
import app.web.qk.service.QkDictService;
import com.gitee.feizns.quickstart.dict.Dict;
import com.gitee.feizns.quickstart.dict.Entry;
import com.gitee.feizns.quickstart.dict.spring.boot.autoconfigure.db.mybatis.flex.pojo.QkDict;
import com.gitee.feizns.quickstart.web.ex.BadRequestException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * qk dict 服务 impl
 * @author feizns
 * @since 2025/9/21
 */
@Service
public class QkDictServiceImpl implements QkDictService {

    @Override
    public Map<String, QkDict> put(Map<String, Object> entries) {
        List<QkDict> e = entries.entrySet().stream().map(entry -> QkDict.of(entry.getKey(), entry.getValue())).toList();
        List<String> updatedKeys = Dict.put(e).stream().map(Entry::getKey).toList();
        return QkDict.find(updatedKeys);
    }

    @Override
    public Entry value(String key) {
        if ( !Config.publicKeys().contains(key) )
            throw new BadRequestException(String.format("禁止访问字典: '%s'", key));
        Entry entry = Dict.get(key);
        if ( entry == null )
            throw new BadRequestException(String.format("字典不存在: '%s'", key));
        return entry;
    }

    @Override
    public Map<String, Object> values(String[] keys) {
        return Arrays.stream(keys)
                .map(this::value)
                .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
    }

    @Override
    public void delete(List<String> keys) {
        keys.forEach(Dict::delete);
    }

}
